//
//  BindLoginViewController.m
//  EyeCare
//
//  Created by 韩盼盼 on 2017/3/15.
//  Copyright © 2017年 HG. All rights reserved.
//

#import "BindLoginViewController.h"
#import "LoginViewController.h"


@interface BindLoginViewController ()<UITextFieldDelegate>
{
    UIView *contentViews;
    
    UITextField *textField_tel;
    UITextField *textField_captch;
    UITextField *textField_pwd;
    UIButton *nextBtn;
    UIButton *agreeBtn;
    int starTime;
    
    
    UIButton *getCaptchBtn;
}

@property (nonatomic,strong) NSMutableArray *mutable_checks;

@end

@implementation BindLoginViewController

-(NSMutableArray *)mutable_checks{
    if (!_mutable_checks) {
        _mutable_checks=[[NSMutableArray alloc]initWithObjects:@"0",@"0", nil];
    }
    return _mutable_checks;
}

- (void)viewDidLoad {
//    self.navBarType = NO;
    [super viewDidLoad];
    [self setTitle:@"绑定手机"];
//    self.navigateBar.titleLabel.text = @"绑定手机";

    self.view.backgroundColor = HGCOLOR(@"f6f6f6");
    [self initWithSubViews];
    // Do any additional setup after loading the view.
}

-(void)initWithSubViews{
    contentViews  = [[UIView alloc]initWithFrame:CGRectMake(0, 64+HGADPT(5), __kScreenWidth, __kScreenHeight -64-HGADPT(5))];
    contentViews.backgroundColor = HGCOLOR(@"ffffff");
    [self.view addSubview:contentViews];
    
    UIImageView *bindImage=[[UIImageView alloc]initWithFrame:CGRectMake((__kScreenWidth - HGADPT(151))/2, HGADPT(70), HGADPT(151), HGADPT(176))];
    bindImage.image =[UIImage imageNamed:@"bind_image"];
    [contentViews addSubview:bindImage];
    
    textField_tel = [[UITextField alloc]initWithFrame:CGRectMake(HGADPT(30), bindImage.bottom+HGADPT(68), __kScreenWidth - 2*HGADPT(30) , HGADPT(120))];
    textField_tel.backgroundColor = HGCOLOR(@"ffffff");
    textField_tel.layer.borderColor = HGCOLOR(@"e1e1e1").CGColor;
    textField_tel.layer.borderWidth = HGADPT(1);
    textField_tel.clipsToBounds = YES;
    textField_tel.delegate = self;
    textField_tel.placeholder = @"请输入手机号码";
    textField_tel.leftView = [self getLeftView:@"login_usertel"];
    textField_tel.leftViewMode = UITextFieldViewModeAlways;
    [textField_tel setValue:@"11" forKey:@"LimitInput"];
    textField_tel.tintColor = HGCOLOR(@"17bcbb");
    textField_tel.rightView = [self getRightView];
    textField_tel.font = HGFont(30);
    textField_tel.clearButtonMode = UITextFieldViewModeUnlessEditing;
    textField_tel.rightViewMode =UITextFieldViewModeAlways;
    [textField_tel addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    textField_tel.keyboardType = UIKeyboardTypeNumberPad;
    [contentViews addSubview:textField_tel];
    
    textField_captch = [[UITextField alloc]initWithFrame:CGRectMake(HGADPT(30), textField_tel.bottom+HGADPT(30), __kScreenWidth - 2*HGADPT(30) , HGADPT(120))];
    textField_captch.placeholder =@"请输入6位短信验证码,15分钟内有效";
    textField_captch.tintColor = HGCOLOR(@"17bcbb");
    textField_captch.backgroundColor = HGCOLOR(@"ffffff");
    textField_captch.layer.borderColor = HGCOLOR(@"e1e1e1").CGColor;
    textField_captch.layer.borderWidth = HGADPT(1);
    textField_captch.clipsToBounds = YES;
    textField_captch.leftView = [self getLeftView:@"login_captch"];
    textField_captch.leftViewMode = UITextFieldViewModeAlways;
    [textField_captch setValue:@"6" forKey:@"LimitInput"];
    textField_captch.keyboardType = UIKeyboardTypeNumberPad;
    textField_captch.font = HGFont(30);
    [textField_captch addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    [contentViews addSubview:textField_captch];
    
    
    
    nextBtn =[[UIButton alloc]initWithFrame:CGRectMake(HGADPT(30), textField_captch.bottom+HGADPT(50), __kScreenWidth - 2*HGADPT(30), HGADPT(120))];
    [nextBtn setTitle:@"绑定登录" forState:UIControlStateNormal];
    [nextBtn setTitleColor:HGCOLOR(@"ffffff") forState:UIControlStateNormal];
    nextBtn.titleLabel.font = HGFont(30);
    nextBtn.backgroundColor = HGColor(221, 221, 221);
    nextBtn.userInteractionEnabled = NO;
    
    [nextBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [contentViews addSubview:nextBtn];
    
    
    
}

-(void)nextAction:(UIButton *)btn
{
    [self.view endEditing:YES];
    [self thirdpartyBindUnlogin];
}


-(UIView *)getLeftView:(NSString *)imgstr{
    UIView *leftView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, HGADPT(88), HGADPT(120))];
    UIImage *image=[UIImage imageNamed:imgstr];
    
    UIImageView *lefticon=[[UIImageView alloc]initWithFrame:CGRectMake(HGADPT(43),(leftView.height- HGADPT(image.size.height))/2 , HGADPT(image.size.width), HGADPT(image.size.height))];
    [leftView addSubview:lefticon];
    lefticon.image =image;
    return leftView;
}

-(UIView *)getRightView
{
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, HGADPT(211), HGADPT(120))];
    getCaptchBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, (rightView.height - HGADPT(70))/2, HGADPT(186), HGADPT(70))];
    [getCaptchBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    //    getCaptchBtn.layer.borderColor = HGCOLOR(@"ff4865").CGColor;
    getCaptchBtn.layer.borderWidth = HGADPT(1);
    //    [getCaptchBtn setTitleColor:HGCOLOR(@"ff4865") forState:UIControlStateNormal];
    getCaptchBtn.titleLabel.font = HGFont(22);
    [rightView addSubview:getCaptchBtn];
    [getCaptchBtn addTarget:self action:@selector(HG_GetCaptch) forControlEvents:UIControlEventTouchUpInside];
    
    [getCaptchBtn setTitleColor:HGColor(221, 221, 221) forState:UIControlStateNormal];
    getCaptchBtn.layer.borderColor = HGColor(221, 221, 221).CGColor;
    getCaptchBtn.userInteractionEnabled = NO;
    
    return rightView;
}

#pragma mark -- 时间倒计时
- (void)startTime
{
    
    starTime=60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(starTime<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [getCaptchBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                getCaptchBtn.userInteractionEnabled = YES;
                [getCaptchBtn setTitleColor:HGCOLOR(@"ff4865") forState:UIControlStateNormal];
                getCaptchBtn.layer.borderColor = HGCOLOR(@"ff4865").CGColor;
            });
        }else{
            
            NSString *strTime = [NSString stringWithFormat:@"%.2d", starTime];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [getCaptchBtn setTitle:[NSString stringWithFormat:@"(%@)s后发送",strTime] forState:UIControlStateNormal];
                [getCaptchBtn setTitleColor:HGColor(221, 221, 221) forState:UIControlStateNormal];
                getCaptchBtn.layer.borderColor = HGColor(221, 221, 221).CGColor;
                
                getCaptchBtn.titleLabel.numberOfLines=2;
                getCaptchBtn.userInteractionEnabled = NO;
                
            });
            starTime--;
        }
    });
    dispatch_resume(_timer);
}

-(void)textFieldEditingChanged:(UITextField *)textField
{
    if (textField_tel == textField) {
        if (textField_tel.text.length>10) {
            textField_tel.text = [textField_tel.text substringToIndex:11];
            if ([HGDataCheck isMobileNumber_str:textField_tel.text]) {
                
                [self checkMobile];
                //                [self.mutable_checks replaceObjectAtIndex:0 withObject:@"1"];
            }
            else{
                
                [MBProgressHUD showSuccess:@"手机号码格式错误"];
                
                [getCaptchBtn setTitleColor:HGColor(221, 221, 221) forState:UIControlStateNormal];
                getCaptchBtn.layer.borderColor = HGColor(221, 221, 221).CGColor;
                getCaptchBtn.userInteractionEnabled = NO;
                [self.mutable_checks replaceObjectAtIndex:0 withObject:@"0"];
                
            }
        }
        else
        {
            [getCaptchBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
            
            starTime = 0;
            [getCaptchBtn setTitleColor:HGColor(221, 221, 221) forState:UIControlStateNormal];
            getCaptchBtn.layer.borderColor = HGColor(221, 221, 221).CGColor;
            getCaptchBtn.userInteractionEnabled = NO;
            [self.mutable_checks replaceObjectAtIndex:0 withObject:@"0"];
        }
    }
    if (textField_captch ==textField) {
        if (textField.text.length>5) {
            textField.text = [textField.text substringToIndex:6];

//            [self HG_CheckCaptch];
            [self.mutable_checks replaceObjectAtIndex:1 withObject:@"1"];

        }
        else
        {
            [self.mutable_checks replaceObjectAtIndex:1 withObject:@"0"];
        }
    }
    [self checkInputContent];
    
}
-(void)checkInputContent
{
    if ([self.mutable_checks containsObject:@"0"]) {
        nextBtn.backgroundColor = HGColor(221, 221, 221);
        nextBtn.userInteractionEnabled = NO;
    }
    else
    {
        nextBtn.backgroundColor = BTN_NORMAL_COLOR;
        nextBtn.userInteractionEnabled = YES;
    }
}



-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField_tel == textField) {
        if (textField.text.length<10) {
            [getCaptchBtn setTitleColor:HGColor(221, 221, 221) forState:UIControlStateNormal];
            getCaptchBtn.layer.borderColor = HGColor(221, 221, 221).CGColor;
            getCaptchBtn.userInteractionEnabled = NO;
            [self.mutable_checks replaceObjectAtIndex:0 withObject:@0];
            [MBProgressHUD showSuccess:textField.text.length==0?@"手机号不能为空！":@"手机号码格式错误"];
            
        }
        
    }
    if (textField_captch == textField) {
        if (textField.text.length<5) {
            [MBProgressHUD showSuccess:@"验证码位数不够！"];
        }
    }
}

#pragma mark - 检测手机号！
-(void)checkMobile
{
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    [params setObject:textField_tel.text forKey:@"mobile"];
//    
//    WS(ws);
//    NSString *url = API_LHF_BASE_URL(MEMBER_MOBILE_CHECK);
//    [HttpRequest requestWhtiURLString:url type:HttpRequestTypeGet parameters:params success:^(id obj) {
//        if ([obj[@"isexist"] intValue]==1) {
//            [self.mutable_checks replaceObjectAtIndex:0 withObject:@"1"];
//            getCaptchBtn.userInteractionEnabled = YES;
//            [getCaptchBtn setTitleColor:HGCOLOR(@"ff4865") forState:UIControlStateNormal];
//            getCaptchBtn.layer.borderColor = HGCOLOR(@"ff4865").CGColor;
//        }
//        else
//        {
//            [HGMBProgressHUD showMessageCenter:@"账户未注册，请先前往注册" inView:self.view];
//            [getCaptchBtn setTitleColor:HGColor(221, 221, 221) forState:UIControlStateNormal];
//            getCaptchBtn.layer.borderColor = HGColor(221, 221, 221).CGColor;
//            getCaptchBtn.userInteractionEnabled = NO;
//            [self.mutable_checks replaceObjectAtIndex:0 withObject:@"0"];
//            
//            
//        }
//        [self checkInputContent];
//    } failure:^(NSError *error) {
//        [ws.view makeToast:error.description];
//    } waitView:ws.view afterDely:0 vc:ws];
    
    
}

#pragma mark - 获取验证码
-(void)HG_GetCaptch
{
    /*
     mobile	√	string	手机号
     type	√	int	短信类型 可选值:1(注册),2(找回密码),5(绑定第三方登陆账户),7(更换绑定手机(发送验证码给新手机))
     */
//    WS(ws);
//    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    [params setObject:textField_tel.text forKey:@"mobile"];
//    [params setObject:@5 forKey:@"type"];
//    
//    NSString *url = API_LHF_BASE_URL(CAPTCHA_SEND_MOBILE);
//    [HttpRequest requestWhtiURLString:url type:HttpRequestTypePost parameters:params success:^(id obj) {
//        BOOL issuccessed = [[obj objectForKey:@"issuccess"] boolValue];
//        if (issuccessed) {
//            [ws startTime];
//            [ws.view makeToast:@"验证码已发送到您的手机..."];
//            [textField_captch becomeFirstResponder];
//        }else
//        {
//            starTime = 0;
//            [ws.view makeToast:@"获取验证码失败..."];
//        }
//    } failure:^(NSError *error) {
//        [ws.view makeToast:error.description];
//    } waitView:ws.view afterDely:0 vc:ws];
    
}

-(void)HG_CheckCaptch
{
    /*
     captcha	√	string	验证码
     mobile	√	string	手机号
     type	√	int	短信类型 可选值:1(注册),2(找回密码),5(绑定第三方登陆账户),7(更换绑定手机(发送验证码给新手机))
     */
    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    [params setObject:textField_captch.text forKey:@"captcha"];
//    [params setObject:textField_tel.text forKey:@"mobile"];
//    [params setObject:@5 forKey:@"type"];
//    WS(ws);
//    NSString *url = API_LHF_BASE_URL(CAPTCHA_CHECK_MOBILE);
//    [HttpRequest requestWhtiURLString:url type:HttpRequestTypePost parameters:params success:^(id obj) {
//        if ([obj[@"istrue"] intValue]==0) {
//            [HGMBProgressHUD showError:@"验证码输入错误" inview:self.view];
//            [self.mutable_checks replaceObjectAtIndex:1 withObject:@"0"];
//        }
//        else
//        {
//            
//            [self.mutable_checks replaceObjectAtIndex:1 withObject:@"1"];
//        }
//        [self checkInputContent];
//
//    } failure:^(NSError *error) {
//        [ws.view makeToast:error.description];
//    } waitView:ws.view afterDely:0 vc:ws];
   
    
}

#pragma mark - 绑定
-(void)thirdpartyBindUnlogin
{
    /*
     captcha	√	string	验证码
     mobile	√	string	手机号
     thirdpartyaccount	√	string	第三方平台关联账户id
     thirdpartytype	√	int	第三方平台类型 可选值:1(qq),2(微信),3(微博),4(淘宝)
     */
    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    [params setObject:textField_captch.text forKey:@"captcha"];
//    [params setObject:textField_tel.text forKey:@"mobile"];
//    [params setObject:[GVUserDefaults standardUserDefaults].thirdpartyaccount forKey:@"thirdpartyaccount"];
//    [params setObject:[NSString stringWithFormat:@"%d",(int)[GVUserDefaults standardUserDefaults].thirdloginType]  forKey:@"thirdpartytype"];
//    
//    WS(ws);
//    [HttpRequest requestWhtiURLString:API_HG_BASE_URL(THIRDPARTY_BIND_UNLOGIN) type:HttpRequestTypePost parameters:params success:^(id obj) {
//        [GVUserDefaults standardUserDefaults].token = [obj objectForKey:@"token"];
//        [GVUserDefaults standardUserDefaults].failuretime = [obj objectForKey:@"failuretime"];
//        [ws getUserInfo];
//
//    } failure:^(NSError *error) {
//        
//    } waitView:ws.view afterDely:0 vc:ws];
   
}

-(void)getUserInfo
{
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    [params setObject:[GVUserDefaults standardUserDefaults].token forKey:@"token"];
//    
//    NSString *url = API_LHF_BASE_URL(MEMBER_INFO);
//    
//    WS(ws);
//    
//    [HttpRequest requestWhtiURLString:url type:HttpRequestTypeGet parameters:params success:^(id obj) {
//        if ([obj isKindOfClass:[NSDictionary class]]) {
//            [ws saveUserInfo:obj];
//        }else
//        {
//            [ws.view makeToast:@"数据类型异常！"];
//        }
//    } failure:^(NSError *error) {
//        [ws.view makeToast:error.description];
//    } waitView:ws.view afterDely:0 vc:ws];
}

-(void)saveUserInfo:(NSDictionary *)obj
{
    
//    [GVUserDefaults standardUserDefaults].userName = [obj objectForKey:@"name"];
//    [GVUserDefaults standardUserDefaults].mobile = [obj objectForKey:@"mobile"];
//    [GVUserDefaults standardUserDefaults].realname = [obj objectForKey:@"realname"];
//    [GVUserDefaults standardUserDefaults].headimg = [obj objectForKey:@"headimg"];
//    [GVUserDefaults standardUserDefaults].balance = [obj objectForKey:@"balance"];
//    [GVUserDefaults standardUserDefaults].sex = [obj objectForKey:@"sex"];
//    
//    NSString *birthday = [NSString stringWithFormat:@"%@",[obj objectForKey:@"birth"]];
//    if (IsAvailableString(birthday)) {
//        [GVUserDefaults standardUserDefaults].birthday = birthday;
//    }else
//    {
//        [GVUserDefaults standardUserDefaults].birthday = @"";
//    }
//    
//    NSString *signature = [NSString stringWithFormat:@"%@",[obj objectForKey:@"signature"]];
//    if (IsAvailableString(signature)) {
//        [GVUserDefaults standardUserDefaults].signature = [obj objectForKey:@"signature"];
//    }else
//    {
//        [GVUserDefaults standardUserDefaults].signature = @"";
//    }
//    
//    if (!IsAvailableString([GVUserDefaults standardUserDefaults].userName)) {
//        LAddUserInfoViewController *next = [[LAddUserInfoViewController alloc] init];
//        [self.navigationController pushViewController:next animated:YES];
//        return;
//    }
//    [GVUserDefaults standardUserDefaults].isLogin = YES;
//    [GVUserDefaults standardUserDefaults].isverified = [obj objectForKey:@"isverified"];
//    
//    [[NSNotificationCenter defaultCenter] postNotificationName:USER_LOGIN_SUCCESSED object:nil];
//    if (self.bindView ==2) {
//        if (self.bindBlock) {
//            self.bindBlock();
//        }
//        [self.navigationController popViewControllerAnimated:YES];
//    }
//    else
//    {
//        [self.navigationController popToRootViewControllerAnimated:YES];
//    }
}



@end
